// 引入依赖模块
const http = require('http')
const url = require('url')
const fs = require('fs')

// 创建server服务
const server = http.createServer((req, res) => {
    res.setHeader('Content-Type', "text/html;charset=utf-8")
    // 接收前端传入的参数
    const obj = url.parse(req.url, true).query
    if (Object.keys(obj).length > 0) {
        // 调用render函数获取与前端匹配的数据并渲染
        let result = render(obj)
        // 渲染
        res.write(result)
        res.end()
    }
    res.end()
})

// 渲染函数
function render(userData) {
    // 把从前端拿到的数据进行解构
    const {
        username,
        password
    } = userData
    if (typeof (username) === undefined || typeof (password) === undefined) {
        return `<h2 style="margin-top: 50px;text-align: center;">输入错误！</h2>`
    }
    // 过滤数据并返回给前端
    let data = JSON.parse(fs.readFileSync('./data.json', 'utf-8'))
    let res = data.find(item => item.username == username && item.password == password)
    if (res === undefined) {
        res = {
            id: data.length,
            username,
            age: 18,
            password,
            hobby: ["打篮球", "Rap"]
        }
        data.push(res)
        fs.writeFileSync('./data.json', JSON.stringify(data))
    }
    return `<h2 style="margin-top: 50px;text-align: center;">恭喜${res.username}登录成功！</h2>
    <table style="margin: 80px auto;border: 1px solid #ccc;border-collapse: collapse;">
        <tr>
            <th style="padding: 10px;text-align: center;">用户名</th>
            <th style="padding: 10px;text-align: center;">年龄</th>
            <th style="padding: 10px;text-align: center;">爱好</th>
        </tr>
        <tr>
            <td style="padding: 10px;border: 1px solid #ccc;text-align: center;">${res.username}</td>
            <td style="padding: 10px;border: 1px solid #ccc;text-align: center;">${res.age}</td>
            <td style="padding: 10px;border: 1px solid #ccc;text-align: center;">${res.hobby.join('  ')}</td>
        </tr>
    </table>`

}

// 开启端口
server.listen(9000, () => {
    console.log('端口已开启，打开 http://127.0.0.1:9000 可进入...');
})